package com.admin.common.utils;

import cn.hutool.core.util.IdUtil;
import com.admin.common.constant.Constant;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 令牌
 *
 * @author sq-lan
 */
@Slf4j
public class TokenUtil {

    public static final String AUTHORITIES_KEY = "user";
    private static JwtParser jwtParser;
    private static JwtBuilder jwtBuilder;

    static {
        byte[] keyBytes = Decoders.BASE64.decode(Constant.JWT_TOKEN_SECRET);
        Key key = Keys.hmacShaKeyFor(keyBytes);
        jwtParser = Jwts.parserBuilder().setSigningKey(key).build();
        jwtBuilder = Jwts.builder().signWith(key, SignatureAlgorithm.HS512);
    }

    public static void main(String[] args) {
        String s = "aaaaa";
        LocalDateTime localDate = LocalDateTime.now();

       /* String token = jwtBuilder
                // 加入ID确保 Token 不冲突
                .setId(IdUtil.simpleUUID())
                .claim(AUTHORITIES_KEY, s)
                .setSubject(s)
                .setExpiration(DateUtil.toDate(localDate.plusMinutes(1)))
                .compact();
        System.out.println(token);*/

        // 过期不能转换
        Claims claims = getClaims("eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiI2YTI5MDc2YmY1OGQ0NDY5OGFlMzdkMmU1YTdkMWJhOSIsInVzZXIiOiJhYWFhYSIsInN1YiI6ImFhYWFhIiwiZXhwIjoxNzIwNTgyMTg4fQ.ZY9rxDwZF-8ZzWRhzB-0QVPA-JTVlvXBj2D4s6_2YjIKGDnXHGsdXjmJxB9VRD9lfQVY3FP4gvdFIf7Odoz3_A");
        Date date = claims.getExpiration();
        log.info("expiration: {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
    }


    /**
     * 创建Token 设置永不过期
     * Token 时间有效性转到 Redis 维护
     *
     * @return /
     */
    public static String generate(String s) {
        return jwtBuilder
                // 加入ID确保 Token 不冲突
                .setId(IdUtil.simpleUUID())
                .claim(AUTHORITIES_KEY, s)
                .setSubject(s)
                .compact();
    }

    /**
     * 依据Token 获取鉴权信息
     *
     * @param token /
     * @return /
     */
    /*Authentication getAuthentication(String token) {
        Claims claims = getClaims(token);
        User principal = new User(claims.getSubject(), "******", new ArrayList<>());
        return new UsernamePasswordAuthenticationToken(principal, token, new ArrayList<>());
    }*/

    public static Claims getClaims(String token) {
        return jwtParser
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 解析 Token
     *
     * @return /
     */
    public static String get(String header) {
        if (StringUtils.hasText(header) && header.startsWith(Constant.JWT_TOKEN_START_WITH)) {
            // 去掉令牌前缀
            return header.replace(Constant.JWT_TOKEN_START_WITH, "");
        }
        return null;
    }

}
